from const.charset_enum import Charset
from generator.gen import Gen
from dto.param import Param


class GenGB2312(Gen):
    def __init__(self, param: Param = None):
        Gen.__init__(self, param)

    def check(self, c, charset):
        """
        About GB2312 Chinese:
            | region  | code           |
            | A1 ~ A9 | special symbol |
            | AA ~ AF | undefined      |
            | B0 ~ D7 | level1 chinese |
            | D8 ~ F7 | level2 chinese |
            | F8 ~ FE | undefined      |

        GB2312 every region has 16*6=96 location, but every location of 0xXXA0, 0xXXFF is unused,
        so every region only has 94(96-2) location.
        Otherwise , the location of [0xD7FA,0xD7FF] is unused also.

        As the font library file in Windows OS is encoded by Unicode always, so we get the font
        image through converting the other charset to Unicode

        :param c: current char
        :param charset: always GB2312
        :return:  0x0000, if this char should not be handled
                  0xA1F5(□), if this char's location in [0xD7FA,0xD7FF] etc.(we need a placeholder)
                  c,      return itself
        """
        if c & 0xFF == 0xFF or c & 0xFF <= 0xA0:
            return 0x0000
        if 0xD7FA <= c <= 0xD7FF:
            c = 0xA1F5
        # convert to Unicode
        try:
            return ord(c.to_bytes(2, byteorder='big').decode(encoding=Charset.GBK.name.lower()))
        except UnicodeDecodeError:
            return ord(0xA1F5.to_bytes(2, byteorder='big').decode(encoding=Charset.GBK.name.lower()))
